<template>
  <view
    v-if="shenheStatus == 0"
    class="order-page"
    :style="{ background: current == 1 ? '#F2F2F2' : '#fff' }"
  >
    <view class="page-head">
      <!-- 拼单时，不可切换门店 -->
      <view class="md-section">
        <view class="md-info">
          <view class="md-name" @click="changeMd">
            <text>{{ pageData.md_name || stores.name }}</text>
            <!-- <i class="iconfont icon-arrow-right" style="color: #262626;font-size: 20rpx;"></i> -->
          </view>
          <view class="md-distance">
            <i class="iconfont icon-a-map"></i>
            <text>{{ $t("diy.distance") }}{{ pageData.distance }}</text>
          </view>
        </view>
      </view>

      <view
        class="friends-collage-box"
        v-if="
          cartSelectData.length && !storeTableNum && cartSelectData.length > 1
        "
      >
        <view class="friends-list">
          <view
            class="friend-item"
            v-for="(item, index) in cartSelectData"
            :key="index"
          >
            <image :src="item.avatar" mode="aspectFill" />
          </view>
          <view class="add-collage-box">
            <i class="iconfont icon-add-select"></i>
            <button open-type="share"></button>
          </view>
        </view>
        <view class="friends-words">{{ $t("alipay.share") }}</view>
      </view>
      <!-- 正常点餐显示轮播图，拼单时不显示轮播 -->

      <view class="swiper-section">
        <u-swiper
          :list="swiper_banners"
          @click="onClickSwiper"
          height="180"
          border-radius="16"
        ></u-swiper>
      </view>
    </view>

    <view :class="['content-section', current === 1 ? 'content-section2' : '']">
      <view :class="['order-shop-tab']">
        <view class="tab-box">
          <view
            class="tab-item"
            @click="current = index"
            v-for="(item, index) in list"
            :key="index"
          >
            <text :class="index == current ? 'font-bold' : ''">{{
              item.name
            }}</text>
            <view
              class="active-line"
              :class="index == current ? 'show' : ''"
            ></view>
          </view>
        </view>

        <view
          class="friends-collage"
          @click="gotoSpellOrder"
          v-if="!storeTableNum"
        >
          <text>{{ $t("alipay.order") }}</text>
          <!-- <button open-type="share" @click="handleSpell"></button> -->
        </view>
      </view>

      <view
        v-if="current == 0"
        :class="[
          'order-select-section',
          diyData.styleType == 2 ? 'layout-column' : ''
        ]"
      >
        <view class="select-left-side">
          <scroll-view scroll-y class="select-left-scroll">
            <view class="classif-list">
              <view
                class="list-item-box"
                :class="[
                  activeSkuList == index ? 'active-list-box' : '',
                  index == activeSkuList + 1 ? 'top-raduis' : '',
                  index == activeSkuList - 1 ? 'bottom-raduis' : ''
                ]"
                v-for="(item, index) in skuData"
                :key="index"
                @click="handleClassifyItem(item, index)"
              >
                <view class="item-content">{{ item.title }}</view>
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="select-right-side">
          <!-- :class="tabFixed ? 'scroll' : ''"
            :scroll-y="tabFixed" -->
          <scroll-view
            scroll-y
            class="scroll-view scroll"
            :scroll-into-view="scrollItem"
            @scrolltoupper="tabFixed = false"
            :upper-threshold="2"
            @scroll="scroll"
          >
            <view
              class="sku-detail-body"
              v-for="(item, index) in skuData"
              :key="index"
              :id="'sku' + item.id"
            >
              <view class="detail-item-title">
                <text>{{ item.title }}</text>
              </view>
              <view
                class="popup-list-item"
                v-for="(sku, i) in item.list"
                :key="i"
                @click="gotoDetail(sku, item)"
              >
                <view class="good-info">
                  <image
                    class="good-pic"
                    :src="sku.goods_pic"
                    mode="aspectFill"
                  />
                  <view class="info-section">
                    <view class="good-name">{{ sku.name }}</view>
                    <view class="good-num"
                      >{{ $t("shop.month") }} {{ sku.sales || 0 }}</view
                    >
                    <view class="good-select">
                      <view class="good-price">
                        <text>￥</text>
                        <text>{{ sku.price | priceBeforeZero }}</text>
                        <text>{{ sku.price | priceAfterZero }}</text>
                      </view>
                      <view class="action-info" v-if="sku.use_attr == 0">
                        <template v-if="sku.select_num">
                          <view class="add" @click.stop="reduceOne(sku)">
                            <i class="iconfont icon-sami-select"></i>
                          </view>

                          <view class="num">{{ sku.select_num }}</view>
                        </template>

                        <view
                          class="add"
                          @click.stop="addOneToBuy(sku, item, i)"
                        >
                          <i class="iconfont icon-add-select"></i>
                        </view>
                      </view>
                      <view
                        class="choose-sku"
                        v-else
                        @click.stop="actionSelectSku(sku, item)"
                      >
                        <text>{{ $t("alipay.sku") }}</text>
                        <view
                          v-if="sku.select_num > 0"
                          class="attr-select-num"
                          >{{ sku.select_num }}</view
                        >
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>

    <scroll-view v-if="current == 1" scroll-y class="shop-card">
      <shopCard class="shopCard"></shopCard>
    </scroll-view>

    <!-- 已选商品弹窗 -->
    <choosedPopup
      :listData="cartSelectData"
      :startUserId="startManId"
      v-if="showChoosePopup"
      @closePopup="showChoosePopup = false"
      @clearCartAll="clearCartAll"
      @clearUserChoosed="clearUserChoosed"
      @selectAddOne="selectAddOne"
      @selectReduceOne="selectReduceOne"
    ></choosedPopup>
    <!-- 商品规格选择弹框 -->
    <!-- sku弹框 -->
    <newSkuPopup
      ref="sku-popup"
      :skuData="{}"
      :goodsInfo="cartGoodInfo"
      :foodExtGoods="food_ext_goods"
      :foodExtGoodsName="food_ext_goods_name"
      @confirm="(e) => setAddgoodsToCart(e.data)"
      @closeSkuPopup="showSkuPopup = !showSkuPopup"
    ></newSkuPopup>
    <!-- 底部按钮 -->
    <footBtn
      :cartSelectData="cartSelectData"
      :cartTotalPrice="cartTotalPrice"
      :cartChoosedNum="cartChoosedNum"
      :storeTableNum="storeTableNum"
      @handleFoot="handleFoot"
      @handleFootBtn="handleFootBtn"
    ></footBtn>
    <!-- 商家故事 -->
    <login-modal></login-modal>

    <!-- 门店没数据时，切换门店 -->
    <noMdGoods v-if="!businessTime"></noMdGoods>
    <transitionPage></transitionPage>
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import Shenhe from "@/components/shenhe/shenhe";
import shopRecommend from "../components/orderMeal/shop-recommend.vue";
import footBtn from "../components/orderMeal/footBtn.vue";
import choosedPopup from "../components/orderMeal/choosedPopup.vue";
import newSkuPopup from "../components/orderMeal/newSkuPopup.vue";
import shopCard from "../components/orderMeal/shopCard.vue";
import { orderMealMixin } from "../mixins/index";
import noMdGoods from "../components/orderMeal/noMdGoods.vue";

export default {
  components: {
    shopRecommend,
    footBtn,
    choosedPopup,
    shopCard,
    newSkuPopup,
    noMdGoods,
    Shenhe
  },
  data() {
    return {
      tabList: [
        {
          name: this.$t("alipay.orderMeal")
        },
        {
          name: this.$t("common.merchants"),
          msg: "故事"
        }
      ],
      tabActive: 0,
      swiper_banners: [],
      recommendList: [],
      chooseData: [], // 已选sku
      showChoosePopup: false,
      skuData: [],
      scrollItem: "sku0",
      activeSkuList: 0,
      skuInfo: {},
      showSkuPopup: false,
      store: {},
      routeData: {},
      order_id: "",
      diyData: {},
      active: "shop",
      list: [
        {
          name: "点餐",
          value: "0"
        },
        {
          name: "商家",
          value: "1"
        }
      ],
      current: 0,
      longitude: "",
      latitude: "",
      mdData: {},
      pageData: {},
      cartGoodInfo: null,
      isFlag: false,
      requestEnd: false,
      goodsCanScroll: false,
      tabPosition: null,
      tabFixed: false,

      md_id: "",

      food_ext_goods: "",
      food_ext_goods_name: "",
      scrollInfo: null
    };
  },
  mixins: [orderMealMixin], //混入文件
  filters: {
    priceBeforeZero(val) {
      if (!val) val = "";
      if (val.indexOf(".") < 0) return `${val}.`;
      return val.substr(0, val.indexOf("."));
    },
    priceAfterZero(val) {
      if (!val) val = "";
      if (val.indexOf(".") < 0) return "00";
      return val.substr(val.indexOf("."), val.length);
    }
  },
  computed: {
    businessTime() {
      let { pageData: data } = this;
      if (!data || !data.md) return true;
      let { end_time, start_time } = data;

      try {
        if (!(start_time && start_time)) {
          return true;
        }
        let starArr = start_time.split(":"),
          endArr = start_time.split(":");
        starArr[0] = Number(starArr[0]);
        starArr[1] = Number(starArr[1]);
        endArr[0] = Number(endArr[0]);
        endArr[1] = Number(endArr[1]);
        // let txt='2022/03/31 23:00:01';
        let nowVal = new Date().getTime(); //现在的时间戳
        let starVal = new Date().setHours(starArr[0], starArr[1], 0, 0); //开始时间的时间戳
        let endVal = 0; //结束时间的时间戳
        if (endArr[0] <= starArr[0]) {
          //结束时间小于开始时间情况下，为第二天停业 天数+1
          let now = new Date();
          now.setDate(now.getDate() + 1);
          endVal = now.setHours(endArr[0], endArr[1], 0, 0);
        } else {
          endVal = new Date().setHours(endArr[0], endArr[1], 0, 0);
        }
        // 返回当前时间戳是否在时间范围内
        return nowVal >= starVal && nowVal < endVal;
      } catch (e) {
        return true;
      }
    },

    popupShowing() {
      let flag = false;
      if (this.showChoosePopup || this.showSkuPopup) {
        flag = true;
      }
      return flag;
    },

    navFontCss() {
      if (this.diyData.styleType != 2) return "";
      if (this.diyData.fontCss) {
        let style = this.diyData.fontCss;
        style.fontSize = style.fontNum * 2 + "rpx";
        return style;
      }
    }
  },
  async onLoad(t) {
    // setTimeout(() => {
    //   this.$nextTick(() => {
    //     this.getTabPosition();
    //   });
    // }, 100);

    //获取支付宝参数点餐
    let orderMealOption = this.$utils.getStorage("orderMealOption");
    this.$utils.removeStorage("orderMealOption");

    if (t.q || orderMealOption) {
      let q = decodeURIComponent(t.q || orderMealOption);
      let scene_index = q.indexOf("scene=");
      let id = q.indexOf("id=");
      let str = "";

      if (id !== -1) {
        let qrcode_id = "";

        qrcode_id = q.substr(q.indexOf("id=") + 3);

        const res = await this.$allrequest.alipay.getQrcodeInfo({
          qrcode_id
        });
        if (!res.code) {
          let { food_table_num, md_id, status } = res.data;
          if (status) {
            this.storeTableNum = food_table_num;
            this.$utils.setStorage("food_table_num", food_table_num);

            if (md_id) {
              this.md_id = md_id;
              this.$utils.setStorage(
                "storeMdData",
                JSON.stringify({
                  id: md_id
                })
              );
            }
          }
        }
      }

      if (scene_index !== -1) {
        str = q.substr(q.indexOf("scene=") + 6);
        t = {
          scene: str
        };

        const url = this.$utils.sceneDecode(decodeURIComponent(t.scene));
        if (url.store_id) {
          this.$store.commit("setStoreId", url.store_id);
        }
      }
    }

    // 判断是否登录
    if (!this.$utils.isLogin(false)) {
      let str = "";
      if (Object.keys(t).length) {
        for (let key in t) {
          str = str + key + "=" + t[key] + "&";
        }
      }
      str = str.substr(0, str.length - 1);
      // 判断是否登录
      this.$store.commit(
        "setNoLoginTabarPath",
        `/alipay-order/orderMeal/orderMeal?${str}`
      );
      this.$store.commit("setRouteType", "redirectTo");
      return;
    }

    // 区分扫码直接进入 获取桌号 md_id门店id(-1平台) food_table_num桌号
    let md_id, food_table_num;
    if (t.scene) {
      uni.removeStorageSync("flag_id");
      this.storeFlagId = "";
      this.storeTableNum = "";

      let params = this.$utils.sceneDecode(t.scene);
      md_id = params.md_id;
      food_table_num = params.food_table_num;
    } else {
      if (t.md_id) {
        md_id = t.md_id;
      }

      if (t.food_table_num) {
        food_table_num = t.food_table_num;
      }

      if (t.flag_id) {
        this.setFlagIdToStorage(t.flag_id);
        this.storeFlagId = t.flag_id;
      }
    }

    this.$utils.setStorage(
      "storeMdData",
      JSON.stringify({
        id: md_id
      })
    );

    // 切换门店 更新数据
    if (uni.getStorageSync("mdBackUrl")) {
      uni.removeStorageSync("mdBackUrl");
      food_table_num = "";
    }

    if (this.storeMdData) {
      md_id = JSON.parse(this.storeMdData).id;
    }

    if (food_table_num) {
      this.storeTableNum = food_table_num;
      this.$utils.setStorage("food_table_num", food_table_num);
    }

    if (md_id === "-1") {
      this.md_id = md_id;
      this.initData();
    } else {
      // 门店数据更新
      this.updateMdData(md_id, () => {
        this.initData();
      });
    }

    this.routeData = t;

    // 获取拼单状态
    if (this.storeFlagId) this.spellOrderStatus(this.storeFlagId);
  },

  onHide() {
    this.clearIntervalPoll = true;
  },

  onUnload() {
    clearInterval(this.intervalPoll);
  },

  async onShow() {
    if (!this.$utils.isLogin(false)) return;

    if (!uni.getStorageSync("flag_id")) {
      this.storeFlagId = "";

      let md_id = -1;
      if (this.storeMdData) {
        md_id = JSON.parse(this.storeMdData).id;
      }
      const res = await this.$allrequest.alipay.initGoodsCart({
        table_num: this.storeTableNum,
        md_id: md_id
      });
      if (!res.code && res.data.flag_id) {
        let { flag_id } = res.data;
        uni.setStorageSync("flag_id", flag_id);
        this.storeFlagId = flag_id;
      }
    }

    clearInterval(this.intervalPoll);
    // 页面显示时，重新开始轮询
    this.pollingCartData();
    this.clearIntervalPoll = false;

    this.startPolling();

  },
  watch: {
    cartSelectData(val) {
      this.updateDataToView();
    },
    current(e) {
      if (!e) {
        this.tabFixed = false;
        this.activeSkuList = 0;
      }
    }
  },
  async onShareAppMessage() {
    const storeId = uni.getStorageSync("store_id");
    let path = `/alipay-order/orderMeal/orderMeal?store_id=${storeId}`;
    if (this.storeTableNum) {
      path = `/alipay-order/orderMeal/orderMeal?food_table_num=${this.storeTableNum}&md_id=${this.storageMdId}&store_id=${storeId}`;
    } else {
      if (this.storeFlagId) {
        path = `/alipay-order/orderMeal/orderMeal?flag_id=${this.storeFlagId}&shareId=${this.startManId}&md_id=${this.storageMdId}&store_id=${storeId}`;
      }
    }
    if (this.isFlag && !this.storeFlagId) {
      let flagData = await this.$allrequest.alipay.createStoreFlagId();
      if (!flagData.code) {
        if (
          this.storeFlagId != flagData.data.flag_id &&
          flagData.data.flag_id
        ) {
          this.setFlagIdToStorage(flagData.data.flag_id);
          this.storeFlagId = flagData.data.flag_id;
          path = `/alipay-order/orderMeal/orderMeal?flag_id=${
            this.storeFlagId
          }&shareId=${this.startManId || "0"}&md_id=${
            this.storageMdId
          }&store_id=${storeId}`;
        }
      }
    }
    return {
      title: "喊你一起点餐～",
      path: path,
      imageUrl: this.stores.store_share_logo,
      desc: this.stores.store_share_desc,
      success(res) {
        uni.showToast({
          title: this.$t("home.success")
        });
      },
      fail(res) {
        uni.showToast({
          title: this.$t("home.fail"),
          icon: "none"
        });
      }
    };
  },
  methods: {
    scroll(e) {
      let { scrollTop } = e.detail,
        { tabPosition, scrollInfo } = this,
        { top, height } = tabPosition,
        heightNum = top + height;

      for (let i in scrollInfo) {
        let { top, height } = scrollInfo[i],
          num = top - heightNum - 1;

        if (scrollTop >= num && scrollTop <= num + height) {
          this.$nextTick(() => {
            this.activeSkuList = i;
          });
          break;
        }
      }
    },
    handleSpell() {
      this.isFlag = true;
    },
    // 点击好友拼单跳转至拼单页
    async gotoSpellOrder() {
      let path = `/alipay-order/spellOrder/index?flag_id=${
        this.storeFlagId
      }&shareId=${this.startManId || ""}`;
      if (!this.storeFlagId) {
        let flagData = await this.$allrequest.alipay.createStoreFlagId();
        if (!flagData.code) {
          if (
            this.storeFlagId != flagData.data.flag_id &&
            flagData.data.flag_id
          ) {
            this.setFlagIdToStorage(flagData.data.flag_id);
            this.storeFlagId = flagData.data.flag_id;
            path = `/alipay-order/spellOrder/index?flag_id=${
              this.storeFlagId
            }&shareId=${this.startManId || ""}`;
          }
        }
      }

      this.$utils.toUrl(path);
    },
    // 同步点餐数据
    updateDataToView() {
      this.skuData.forEach((d) => {
        d.list.forEach((k) => {
          k.select_num = 0;
          k.user_num = 0;
          k.other_num = 0;
          for (let i = 0; i < this.cartSelectData.length; i++) {
            for (let n = 0; n < this.cartSelectData[i].goods_list.length; n++) {
              if (
                this.user_id == this.cartSelectData[i].user_id &&
                k.id == this.cartSelectData[i].goods_list[n].goods_id
              ) {
                k.cart_id = this.cartSelectData[i].goods_list[n].cart_id;
                k.user_num =
                  k.user_num + this.cartSelectData[i].goods_list[n].num;
              }

              if (
                this.user_id != this.cartSelectData[i].user_id &&
                k.id == this.cartSelectData[i].goods_list[n].goods_id
              ) {
                k.cart_id = this.cartSelectData[i].goods_list[n].cart_id;

                k.other_num =
                  k.other_num + this.cartSelectData[i].goods_list[n].num;
              }
            }
          }
          k.select_num = k.user_num + k.other_num;
        });
      });
    },
    // 开始轮询数据
    startPolling() {
      setTimeout(() => {
        this.intervalPollingCartData();
      }, 3000);
    },
    async initData() {
      const res = await this.$store.dispatch("getLocation");
      if (res) {
        let { longitude, latitude } = res;
        this.longitude = longitude;
        this.latitude = latitude;
      }
      this.getPageData();
    },

    // 获取点餐首页店铺数据
    getPageData() {
      let {
        storageMdId,
        md_id,
        active: type,
        latitude: lat,
        longitude: lng
      } = this;

      this.$allrequest.alipay
        .getOrderMealPageData({
          md_id: md_id || storageMdId,
          type,
          lat,
          lng
        })
        .then((res) => {
          this.requestEnd = true;
          if (!res.code) {
            this.pageData = res.data;
            this.swiper_banners = res.data.banner;
            let data = res.data.goods_list;
            data.forEach((d) => {
              d.list.forEach((i) => {
                i["select_num"] = 0;
              });
            });
            this.skuData = data;
            this.updateDataToView();

            this.$nextTick(async () => {
              if (data && data.length) {
                let obj = {};
                data.forEach(async (el, i) => {
                  let domEl = `#sku${el.id}`;

                  let query = null;
                  // #ifdef MP-ALIPAY
                  query = uni.createSelectorQuery();
                  // #endif
                  // #ifndef MP-ALIPAY
                  query = uni.createSelectorQuery().in(this);
                  // #endif
                  query
                    .select(domEl)
                    .boundingClientRect(({ top, height }) => {
                      obj[i] = { top, height };

                      if (i == data.length - 1) {
                        this.scrollInfo = obj;
                      }
                    })
                    .exec();
                });
              }

              this.getTabPosition();
            });
          }
        });
    },
    // 获取diy后台配置的数据
    getDiyData() {
      uni.showLoading({
        title: this.$t("home.loading")
      });
      this.$allrequest.diyNew
        .getDiySystemPages()
        .then((res) => {
          if (!res.code) {
            let list = res.data.list;
            let data = {};
            if (!list.length) return;
            list.forEach((d) => {
              d.template = JSON.parse(d.template);
              if (d.template.system_type == "orderMeal") {
                data = d;
              }
            });
            if (!data?.id) return;
            let diyData = data.template.templates[0].params;
            this.diyData = diyData;
            uni.hideLoading();
          } else {
            uni.hideLoading();
          }
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
    sendTypeChange(type) {
      this.active = type;
      this.getPageData();
    },
    // 点击轮播图
    onClickSwiper: function (index) {
      const link = this.swiper_banners[index].link;
      this.$utils.toUrl(link);
    },
    // tab切换
    tabChange(tab, index) {
      this.tabActive = index;
    },
    //  点击商家推荐加购回调
    recommendAddBuy(e) {
      let item = Object.assign({}, e.item);
      for (let i = 0; i < this.recommendList.length; i++) {
        if (item.id == this.recommendList[i].id) {
          this.recommendList[i]["select_num"] = item.select_num;
        }
      }
      // delete item.num;
      this.chooseData.push(item);
    },
    // 点击页面底部，弹出已选sku弹框
    handleFoot() {
      this.showChoosePopup = !this.showChoosePopup;
    },
    // 处理请求参数
    dealRequestData() {
      let arr = JSON.parse(JSON.stringify(this.chooseData));
      // 组装数据
      arr.forEach((d) => {
        if (d?.sku) {
          d["attr"] = d.sku;
        } else {
          d["attr"] = [];
        }
        d["pic"] = d.goods_pic;
        d["select_num"] = 1;
      });
      // 选择数据去重及合并
      let cache = [],
        repeat = [];
      for (let t of arr) {
        if (cache.find((c) => c.id === t.id)) {
          repeat.push(t);
          continue;
        }
        cache.push(t);
      }

      cache.forEach((d) => {
        repeat.forEach((i) => {
          if (d.id == i.id && d.attr.toString() == i.attr.toString()) {
            d.select_num++;
          }
          if (d.id == i.id && d.attr.toString() != i.attr.toString()) {
            cache.push(i);
            repeat.splice(i, 1);
          }
        });
      });
      return cache;
    },
    // 点击底部按钮组件回调。去结算
    handleFootBtn() {
      uni.showToast({
        title: this.$t("home.loading"),
        duration: 2000,
        icon: "none"
      });

      // 好友拼单
      if (
        this.storeFlagId &&
        !this.storeTableNum &&
        this.cartSelectData.length > 1
      ) {
        this.$utils.toUrl(
          `/alipay-order/spellOrder/index?flag_id=${this.storeFlagId}&shareId=${this.startManId}`
        );
      }

      // 桌号点餐
      if (this.storeTableNum || this.cartSelectData.length <= 1) {
        let mch_info = {
          mch_id: 0,
          goods_list: []
        };
        let arr = [];
        this.cartSelectData.forEach((d) => {
          d.goods_list.forEach((k) => {
            let item = {};
            item["food_cart_id"] = k.cart_id;
            arr.push(item);
          });
        });
        mch_info.goods_list = arr;
        let params = {
          mch_list: JSON.stringify([mch_info]),
          flag_id: this.storeFlagId,
          table_num: this.storeTableNum
        };

        this.$utils.toUrl(
          `/alipay-order/order/order?order_info=${JSON.stringify(
            params
          )}&mealType=${this.active}`
        );
      }
    },
    // 清空选择的商品
    clearChoosed(e) {
      this.chooseData = [];
      this.skuData.forEach((d) => {
        d.list.forEach((i) => {
          i.select_num = 0;
        });
      });
      this.showChoosePopup = false;
    },
    // 清空用户所选商品
    clearUserChoosed(e) {
      let user_id = e.user_id;
      this.emptyUserCart(user_id, () => {
        this.showChoosePopup = false;
      });
    },
    // 清空购物车
    clearCartAll() {
      this.emptyCart(() => {
        this.showChoosePopup = false;
      });
    },
    // 已选弹框添加一个回调
    selectAddOne(e) {
      let item = JSON.parse(JSON.stringify(e.item));

      if (typeof item.food_ext_goods !== "string") {
        item.food_ext_goods = JSON.stringify(item.food_ext_goods);
      }

      let attr = item.attr_list;
      attr.forEach((d) => {
        d["attr_id"] = d.id;
      });
      let params = {
        attr: JSON.stringify(attr),
        num: 1,
        goods_id: item.goods_id,
        food_ext_goods: item.food_ext_goods
      };
      this.addGoodsToCart(params, () => {
        this.pollingCartData(() => {
          this.updateDataToView();
        });
      });
    },

    // 已选弹框删除一个回调
    selectReduceOne(e) {
      this.reduceOneCartNum(e, () => {
        this.pollingCartData(() => {
          if (!this.cartSelectData.length) {
            this.showChoosePopup = false;
          }
          this.updateDataToView();
        });
      });
    },

    // 添加一个商品
    addOneToBuy(sku, item, i) {
      if (sku.num <= 0) {
        uni.showToast({
          title: this.$t("alipay.noCount"),
          icon: "none"
        });
        return;
      }

      let data = Object.assign({}, sku);

      let attr = sku.attr_group_list[0];
      attr = [
        {
          attr_group_id: attr.attr_group_id,
          attr_group_name: attr.attr_group_name,
          attr_id: attr.attr_list[0].attr_id,
          attr_name: attr.attr_list[0].attr_name
        }
      ];
      let params = {
        attr: JSON.stringify(attr),
        num: 1,
        goods_id: sku.id || sku.goods_id
      };

      if (sku.food_ext_goods) {
        this.food_ext_goods = sku.food_ext_goods;
        this.cartGoodInfo = sku;
        this.$refs["sku-popup"].showPopup(0, data);
      } else {
        this.food_ext_goods = "";
        this.setAddgoodsToCart(params);
      }
    },

    // 加入购物车
    setAddgoodsToCart(params) {
      this.addGoodsToCart(params, () => {
        this.showSkuPopup = false;
        this.food_ext_goods = "";
        this.food_ext_goods_name = "";
        this.cartGoodInfo = null;
        this.$refs["sku-popup"].closePopup();
        this.pollingCartData(() => {
          this.updateDataToView();
        });
      });
    },

    // 删除一个商品
    reduceOne(item) {
      if (item.select_num <= 0) return;
      if (item.user_num <= 0) return;
      item.select_num--;
      item.user_num--;
      if (item.num <= 0) {
        item.num = 0;
      }
      let params = {
        cart_id: item.cart_id,
        num: this.storeTableNum ? item.user_num : item.select_num
      };
      this.reduceOneCartNum(params, () => {
        this.pollingCartData(() => {
          this.updateDataToView();
        });
      });
    },

    // 点击选择规格
    actionSelectSku(sku, item) {
      this.cartGoodInfo = sku;
      sku["stamp"] = `skuBox-${item.id}-${sku.id}`;
      this.skuInfo = sku;
      this.food_ext_goods = sku.food_ext_goods;
      this.food_ext_goods_name = sku.food_ext_goods_model
        ? sku.food_ext_goods_model.name
        : "";
      this.$refs["sku-popup"].showPopup();
    },

    // 商品规格选择弹框点击选好了回调
    chooseEnd(e) {
      this.skuInfo = e.data;
      this.showSkuPopup = false;
      let item = Object.assign({}, e.data);
      let [a, b, c] = item.stamp.split("-");
      if (a && a == "skuBox") {
        this.skuData.forEach((d) => {
          if (d.id == b) {
            for (let i = 0; i < d.list.length; i++) {
              if (d.list[i].id == c) {
                d.list[i].select_num = item.select_num;
                d.list[i]["sku"] = item.sku;
                break;
              }
            }
          }
        });
      }
      let arr = this.chooseData.filter((d) => {
        return d.stamp != item.stamp;
      });
      item["skuNum"] = item.select_num;
      delete item.select_num;
      for (let i = 0; i < e.data.select_num; i++) {
        arr.push(item);
      }
      this.chooseData = arr;
    },
    // 点击左侧菜单
    handleClassifyItem(item, index) {
      this.activeSkuList = index;
      if (!index) {
        this.tabFixed = true;
      }

      setTimeout(() => {
        uni.pageScrollTo({
          duration: 300,
          selector: "#sku" + item.id,
          complete: (res) => {
            setTimeout(() => {
              this.scrollItem = "sku" + item.id;
            }, 100);
          }
        });
      }, 0);
    },
    // 跳转商品详情
    gotoDetail(sku, item) {
      this.$utils.toUrl(`/alipay-order/goods/goods?id=${sku.id}`);
    },
    // 跳转商家详情
    gotoShop() {
      this.$utils.toUrl("/alipay-order/shop/shop");
    },
    // 点击切换门店
    changeMd() {
      if (this.storeTableNum) return;
      if (this.cartSelectData.length > 1) return;

      uni.removeStorageSync("flag_id");
      uni.removeStorageSync("food_table_num");
      let str = "";
      if (Object.keys(this.routeData).length) {
        for (let key in this.routeData) {
          str = str + key + "=" + this.routeData[key] + "&";
        }
      }
      str = str.substr(0, str.length - 1);

      uni.setStorageSync(
        "mdBackUrl",
        `/alipay-order/orderMeal/orderMeal?${str}`
      );
      this.$utils.toUrl(
        `/pages/md/md-list?url=/alipay-order/orderMeal/orderMeal?${str}`
      );
    },
    stickyFixed() {
      this.goodsCanScroll = true;
    },
    stickyUnFixed() {
      this.goodsCanScroll = false;
    },
    getTabPosition() {
      let query;
      // #ifdef MP-ALIPAY
      query = uni.createSelectorQuery();
      // #endif
      // #ifndef MP-ALIPAY
      query = uni.createSelectorQuery().in(this);
      // #endif

      query
        .select(".order-shop-tab")
        .boundingClientRect((data) => {
          this.$nextTick(() => {
            this.tabPosition = data;
          });
        })
        .exec();
    }
  },

  onPageScroll(e) {
    if (this.tabPosition) {
      if (this.tabPosition.top <= e.scrollTop) {
        if (!this.tabFixed) {
          this.tabFixed = true;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
page {
  position: relative;
}

.order-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  // padding-bottom: 13.07vw;

  .page-head {
    width: 100%;
    position: relative;

    .md-section {
      width: 100%;
      height: 124rpx;
      background: #ffffff;
      padding: 0 24rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      overflow: hidden;

      .md-info {
        .md-name {
          display: flex;
          align-items: center;
          text {
            font-size: 30rpx;
            font-weight: 600;
            color: #262626;
          }
        }
        .md-distance {
          display: flex;
          align-items: center;
          margin-top: 8rpx;
          text {
            font-size: 24rpx;
            font-weight: 400;
            color: #8c8c8c;
          }
          .iconfont {
            color: #8c8c8c;
          }
        }
      }
      .send-section {
        width: 88rpx;
        height: 48rpx;
        background: #f2f2f2;
        border-radius: 88rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .left {
          width: 50%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 24rpx;
          font-weight: 400;
          color: #262626;
        }
        .right {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 24rpx;
          font-weight: 400;
          color: #262626;
        }
        .select {
          background: #f60313;
          border-radius: 88rpx;
          color: #ffffff;
        }
      }
    }
    .friends-collage-box {
      width: 100%;
      height: 180rpx;
      padding: 24rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      background-color: #ffffff;
      .friends-list {
        height: 60rpx;
        width: 100%;
        display: flex;
        align-items: center;
        overflow-x: scroll;
        overflow-y: hidden;
        .friend-item {
          width: 60rpx;
          height: 60rpx;
          background: #fbeceb;
          border: 1px solid #f1f1f1;
          border-radius: 50%;
          margin-left: 16rpx;
          overflow: hidden;
          image {
            width: 100%;
            height: 100%;
            display: block;
          }
        }
        .friend-item:first-child {
          margin-left: 0;
        }
        .add-collage-box {
          width: 60rpx;
          height: 60rpx;
          background: #fbeceb;
          border: 1px dashed #f60313;
          border-radius: 50%;
          margin-left: 16rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          position: relative;
          .iconfont {
            color: #f0250e;
            font-size: 36rpx;
          }
          button {
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
          }
        }
      }
      .friends-words {
        font-size: 26rpx;
        font-weight: 400;
        color: #8c8c8c;
      }
    }

    .swiper-section {
      width: 100%;
      padding: 0 24rpx;
    }
  }
  .sticky-box {
    width: 100%;
    margin-top: 13.6vw;

    .tabs-section {
      width: 100%;
      height: 12vw;
      padding: 0 3.2vw;
      display: flex;
      align-items: center;
      background-color: #ffffff;

      .tab-item {
        width: 20vw;
        display: flex;
        font-size: 4.27vw;
        font-weight: 400;
        color: #191919;
        .tab-name {
          display: flex;
          flex-direction: column;
          align-items: center;
          .line {
            width: 5.33vw;
            height: 0.8vw;
            margin-top: 0.53vw;
          }
          .active-line {
            background: #1fb6fd;
          }
        }
        .tab-msg {
          font-size: 2.93vw;
          font-weight: 400;
          color: #999999;
          margin-left: 0.8vw;
          line-height: 4.5vw;
        }
      }
    }
  }

  .content-section {
    flex: 1;
    overflow: hidden;
    // position: sticky;
    // left: 0;
    // top: 0;
    // width: 100%;
    // height: 100vh;
    display: flex;
    flex-direction: column;
    padding-bottom: env(safe-area-inset-bottom);
    box-sizing: border-box;

    &.content-section2 {
      height: auto;
      position: static;
      padding-bottom: 0;
      flex: inherit;
    }

    .order-shop-tab {
      width: 100%;
      height: 90rpx;
      padding: 0 24rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #ffffff;
      .friends-collage {
        width: 128rpx;
        height: 50rpx;
        border: 1px solid #f60313;
        border-radius: 64rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #f60313;
        text-align: center;
        line-height: 50rpx;
        position: relative;
        button {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          opacity: 0;
        }
      }
      .tab-box {
        height: 100%;
        display: flex;
        align-items: center;
        .tab-item {
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-left: 80rpx;
          text {
            font-size: 32rpx;
            font-weight: 400;
            color: #262626;
          }
          .font-bold {
            font-weight: 600;
          }
          .active-line {
            width: 40rpx;
            height: 6rpx;
            background: #f60313;
            margin-top: 6rpx;
            opacity: 0;
          }
          .show {
            opacity: 1;
          }
        }
        .tab-item:first-child {
          margin-left: 0;
        }
      }
    }

    .order-select-section {
      position: relative;
      width: 100%;
      flex: 1;
      overflow: hidden;
      display: flex;
      padding-bottom: 140rpx;

      .select-left-side {
        width: 21.33vw;
        background: #f2f2f2;
        height: 100%;
        .classif-list {
          width: 100%;
          // height: 14.13vw;
          background-color: #ffffff;

          .list-item-box {
            width: 100%;
            padding: 27rpx 0;
            display: flex;
            justify-content: center;
            background-color: #f2f2f2;
            .item-content {
              width: 84%;
              text-align: center;
              font-size: 26rpx;
              font-weight: 400;
              color: #8c8c8c;
            }
          }
          .active-list-box {
            background: #ffffff;
          }
          .top-raduis {
            border-radius: 0 20rpx 0 0;
          }
          .bottom-raduis {
            border-radius: 0 0 20rpx 0;
          }
        }
      }
      .select-right-side {
        flex: 1;
        overflow: hidden;
        // padding-top: 2.93vw;
        height: 100%;
        // padding-bottom: 280rpx;
        box-sizing: border-box;

        scroll-view {
          height: 100%;
          width: 100%;
          overflow-y: hidden;

          &.scroll {
            overflow-y: auto;
          }

          &::-webkit-scrollbar {
            width: 0;
            height: 0;
          }
        }

        .sku-detail-body {
          padding: 6.4vw 24rpx 0 24rpx;
          width: 100%;
          overflow: hidden;
        }
        .sku-detail-body:first-child {
          padding-top: 8rpx;
        }

        .detail-item-title {
          display: flex;
          align-items: flex-end;
          font-size: 3.2vw;
          font-weight: 400;
          line-height: 4.27vw;
          color: #999999;
          margin-bottom: 28rpx;
          text:first-child {
            font-size: 3.73vw;
            font-weight: 600;
            color: #191919;
            margin-right: 1.07vw;
          }
        }

        .popup-list-item {
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          margin-bottom: 6.4vw;
          width: 100%;
          .good-info {
            width: 100%;
            display: flex;
            align-items: flex-start;
            .good-pic {
              width: 192rpx;
              height: 192rpx;
              background: #f2f2f2;
              border-radius: 10rpx;
              display: block;
              margin-right: 20rpx;
              flex-shrink: 0;
            }
            .info-section {
              flex: 1;
              .good-name {
                font-size: 30rpx;
                font-family: PingFang SC;
                font-weight: 600;
                line-height: 40rpx;
                color: #262626;
                word-break: break-all;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2; /* 这里是超出几行省略 */
                overflow: hidden;
              }
              .good-sku {
                max-width: 40.27vw;
                font-size: 3.2vw;
                font-weight: 400;
                line-height: 4.27vw;
                color: #999999;
                margin-top: 1.07vw;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
              .good-num {
                font-size: 24rpx;
                font-weight: 400;
                color: #8c8c8c;
                margin-top: 10rpx;
              }
              .good-select {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top: 10rpx;
              }
              .good-price {
                display: flex;
                align-items: baseline;
                font-size: 24rpx;
                font-weight: 600;
                color: #f0250e;

                text:nth-child(2) {
                  font-size: 38rpx;
                }
              }
            }
          }
          .action-info {
            display: flex;
            align-items: center;
            .reduce {
              width: 44rpx;
              height: 44rpx;
              background: #ffffff;
              border-radius: 16rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              border: 1px solid #f60313;
              view {
                width: 24rpx;
                height: 4rpx;
                background: #f0250e;
              }
            }
            .disabled {
              background: #f1f1f1;
              border: 0 none;
              view {
                background: #ffffff;
              }
            }
            .num {
              font-size: 3.73vw;
              font-weight: 400;
              line-height: 4.27vw;
              color: #191919;
              margin: 0 2.93vw;
            }
            .add {
              width: 44rpx;
              height: 44rpx;
              background: #f60313;
              border-radius: 16rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              .iconfont {
                color: #ffffff;
                font-weight: bold;
                font-size: 36rpx;
              }
            }
          }
          .choose-sku {
            width: 100rpx;
            height: 44rpx;
            background: #f60313;
            border-radius: 16rpx;
            text-align: center;
            line-height: 44rpx;
            font-size: 24rpx;
            font-weight: 600;
            color: #ffffff;
            position: relative;
            .attr-select-num {
              width: 32rpx;
              height: 32rpx;
              background: #f84a33;
              border-radius: 50%;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 20rpx;
              font-family: PingFang SC;
              font-weight: 600;
              color: #ffffff;
              position: absolute;
              right: -16rpx;
              top: -16rpx;
            }
          }
        }
        .popup-list-item:last-child {
          margin-bottom: 0;
        }
      }
    }

    .layout-column {
      flex-direction: column;
      align-items: center;
      .select-left-side {
        width: 100%;
        background: none;

        .classif-list {
          width: 100vw;
          height: 14.13vw;
          display: flex;
          justify-content: space-around;
          align-items: center;
          background-color: #ffffff;
          .list-item-box {
            flex-shrink: 0;
            width: initial;
            height: 100%;
            .list-item {
              width: 100%;
              height: 100%;
              padding: 0;
              display: flex;
              justify-content: center;
              align-items: center;
              flex-direction: column;
              .item-inner {
                display: flex;
                align-items: center;
              }
              .active-line {
                width: 100%;
                height: 4rpx;
                background: #fa2c1b;
                margin-top: 1.067vw;
                opacity: 0;
              }
              .show-line {
                opacity: 1;
              }
            }
          }
        }
      }
      .select-right-side {
        flex: 1;
        overflow: hidden;
        .sku-detail-body {
          width: 100%;
          .popup-list-item {
            width: 100%;
            .good-info {
              width: 100%;
              .info-section {
                flex: 1;
                .good-select {
                  width: 100%;
                }
              }
            }
          }
        }
      }
    }
  }
}

.shopCard {
  padding-bottom: calc(env(safe-area-inset-bottom) + 140rpx);
}

.select-left-scroll {
  height: 100%;
  overflow-y: auto;
}

.shop-card {
  flex: 1;
  overflow-y: auto;
}
</style>
